﻿using System;
using System.Collections.Generic;
using System.Text;
using UMLDesigner.Widgets;
using System.Drawing;
using UMLDesigner.WorkUnits;
using UMLDesigner.Page;

namespace UMLDesigner
{
    public class Document
    {
        public Document()
        {
            widgets = new LinkedList<UMLWidget>();
            history = new History(this);
        }

        public LinkedList<UMLWidget> Widgets
        {
            get
            {
                return widgets;
            }
        }

        public virtual void AddWidget(UMLWidgetType type)
        {

        }

        public void AddWidget(UMLWidget widget)
        {
            widget.Location = GetNextItemLocation();
            widgets.AddLast(widget);
            UMLPage.Invalidate();
        }

        public Point GetNextItemLocation()
        {
            const int increment = 100;
            Point result = new Point();
            result.X = -result.X + increment;
            result.Y = -result.Y + increment;

            while (GetWidgetAtPoint(result) != null)
            {
                result.X += increment;
                if (result.X > UMLPage.Width - increment)
                {
                    result.Y += increment;
                    result.X = increment;
                }
            }

            return result;
        }

        public void RemoveWidget(UMLWidget widget)
        {
            foreach (UMLWidget w in widgets)
            {
                if (w == widget)
                {
                    widgets.Remove(widget);
                    break;
                }
            }
        }

        public void Redo()
        {
            history.Redo();
        }

        public void Undo()
        {
            history.Undo();
        }

        public UMLWidget GetWidgetAtPoint(Point point)
        {
            foreach (UMLWidget w in widgets)
            {
                if (w.IsIn(point) == true)
                {
                    return w;
                }
            }
            return null;
        }

        public UMLPage UMLPage
        {
            get;
            set;
        }

        public bool IsModified
        {
            get;
            set;
        }

        public History History
        {
            get
            {
                return history;
            }
        }


        private LinkedList<UMLWidget> widgets;
        protected History history;
    }
}
